#include "iaction.h"
#include <QtCore>

void IAction::setParam(const QJsonObject &param)
{
    actParam = param;
}

void IAction::replaceValue(QString match, QString newVal)
{
    qInfo()<<QString("replace ${%1} to").arg(match)<<newVal;
    QJsonDocument tmpDoc(actParam);
    QByteArray paramBA = tmpDoc.toJson(QJsonDocument::Compact);
    paramBA.replace(QString("${%1}").arg(match),newVal.toUtf8());
    actParam = QJsonDocument::fromJson(paramBA).object();
}

void IAction::setNext(IAction *act,int index)
{
    if(actionNext.count()>index)
    {
        actionNext[index] = act;
    }
    else
    {
        for(int i=actionNext.count();i<=index;i++)
        {
            if(i==index)
            {
                actionNext.push_back(act);
                Q_ASSERT(actionNext[index]==act);
            }
            else
            {
                actionNext.push_back(NULL);
            }
        }
    }
}

void IAction::setPrev(IAction *act, int index)
{
    act->setNext(this,index);
}

int IAction::doExec()
{
    int ret = 0;
    actResult = prevResult;  //使默认情况，上次结果可以继承传递下去.
    qDebug()<<"  -exe- param:"<<actParam;
    ret = this->execute();
    qDebug()<<"  -exe- result("<<ret<<"):"<<actResult;
    prevResult = this->actResult;
    return ret;
}

IAction *IAction::getNext(int index)
{
    if(index<0 || index>=actionNext.count()) return NULL;
    return actionNext.at(index);
}

IAction *IAction::create(QString name)
{
    if(name == "CompositeKey"){
        return new ActionCompositeKey();
    }
    if(name == "Condition"){
        return new ActionCondition();
    }
//    if(name == "FindQQLogin"){
//        return new ActionFindQQLogin();
//    }
    if(name == "FindWindow"){
        return new ActionFindWindow();
    }
    if(name == "Hold"){
        return new ActionHold();
    }
    if(name == "Input"){
        return new ActionInput();
    }
    if(name == "Kill"){
        return new ActionKill();
    }
    if(name == "Match"){
        return new ActionMatch();
    }
    if(name == "Mouse"){
        return new ActionMouse();
    }
    if(name == "Process"){
        return new ActionProcess();
    }
    if(name == "QQLogin"){
        return new ActionQQLogin();
    }
    if(name == "RelativePos"){
        return new ActionRelativePos();
    }
    if(name == "Wait"){
        return new ActionWait();
    }


    return NULL;
}

int IAction::freeAllActions()
{
    foreach(IAction* ac, allActions)
    {
        delete ac;
    }
    int count = allActions.count();
    allActions.clear();
    return count;
}

IAction::IAction()
    : classname("IAction-subclass")
{
//    if(allActions.count())
//    {   //当不发生覆盖的情况下,自动把上一个和当前这个连接起来
//        IAction *last = allActions.last();
//        if(last->getNext()==NULL)
//        {
//            this->setPrev(last);
//        }
//    }
    allActions << this;
}

IAction::~IAction()
{

}
QJsonObject IAction::prevResult;
QList<IAction*> IAction::allActions;
